package com.example.sentinel.infrastructure.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;

@Configuration
public class SentinelConfig {
    //资源名，联系规则和被拦截的资源
    private static final String RESOURCE_NAME="processResource";
    
    @PostConstruct
    public void initRules(){
        initFlowRules();
        initDegradeRules();
    }
    
    //初始化限流规则
    private void initFlowRules(){
        ArrayList<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        //让规则绑定资源名
        rule.setResource(RESOURCE_NAME);
        //设置限流规则类型为QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //每秒最多访问5次
        rule.setCount(5);
        //设置资源所属应用，默认为所有
        rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
        rules.add(rule);
        FlowRuleManager.loadRules( rules);
    }
    
    //初始化熔断规则
    private void initDegradeRules(){
        ArrayList<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(RESOURCE_NAME);
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
        //熔断异常比例50%
        rule.setCount(0.5);
        //熔断时长5秒，五秒后放行少量请求，如果异常比例小于50%则恢复正常，否则继续熔断
        rule.setTimeWindow(5);
        //熔断最小请求数，如果请求量太少，即使异常比例很高，也不会熔断
        rule.setMinRequestAmount(20);
        //统计时长10秒
        rule.setStatIntervalMs(10000);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
    
}
